package com.feihong.yw189.paidan.adapter;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.bean.IdInfo;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.paidan.bean.ListOrderInfo;
import com.feihong.yw189.paidan.dialog.PaiDanShuoMingDialog;
import com.feihong.yw189.paidan.dialog.TuiDanDialog;
import com.feihong.yw189.paidan.inter.AddPhoneNumItemListener;
import com.feihong.yw189.paidan.inter.BeiZhuListener;
import com.feihong.yw189.paidan.inter.RefOrderListListener;
import com.feihong.yw189.paidan.inter.TuiDanListListener;
import com.feihong.yw189.paidan.qiangdanservice.LocationSDKTools;
import com.feihong.yw189.paidan.qiangdanservice.LocationUtils;
import com.feihong.yw189.paidan.tools.RefReshToken;
import com.feihong.yw189.utils.SelectDataUtils;
import com.google.gson.Gson;
import com.holenzhou.pullrecyclerview.BaseRecyclerAdapter;
import com.holenzhou.pullrecyclerview.BaseViewHolder;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import me.shaohui.bottomdialog.BottomDialog;

/**
 * 2018/1/24
 * 本数据适配器利用了 orderItemBean.getCity();来刷新item,如果项目中用到了这个值就得换其他值
 * 如果已完成就把状态跟在地址后面,并显示同步和取消按钮
 * 如果是其他状态就直接现在是在原来的位置
 */

public class HoistryListAdapter extends BaseRecyclerAdapter<ListOrderInfo.DataBean.OrderItemBean> {

    private String buyerMobil = "";
    private Context mContext;
    private Activity mActivity;
    private List<ListOrderInfo.DataBean.OrderItemBean> dataList = new ArrayList<>();
    private BottomDialog locationDialog;
    private MyUsualyDialog dialog;
    private PopupWindow popupWindow;
    private String mCopiedText;
    private String order_type;
    private ListOrderInfo.DataBean.OrderItemBean curentItem = null; // 当前item

    /**
     * @param context
     */
    public HoistryListAdapter(Context context) {
        super(context, R.layout.history_item_dispatch, new ArrayList<ListOrderInfo.DataBean.OrderItemBean>());
        this.mContext = context;
        this.mActivity = (Activity) context;
        initPopupWindow();
        dialog = new MyUsualyDialog(mActivity, R.layout.chuli_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);
        locationDialog = BottomDialog.create(((AppCompatActivity) mContext).getSupportFragmentManager())
                //注意Adapter属于的Activity必须继承AppCompatActivity
                .setViewListener(mapSheetView -> {
                    // 可以进行一些必要对View的操作
                    // you can do bind view operation
                    mapSheetView.findViewById(R.id.baidu_btn).setOnClickListener(new HoistryListAdapter.locationButtonListener());
                    mapSheetView.findViewById(R.id.gaode_btn).setOnClickListener(new HoistryListAdapter.locationButtonListener());
                    mapSheetView.findViewById(R.id.tencent_btn).setOnClickListener(new HoistryListAdapter.locationButtonListener());
                    mapSheetView.findViewById(R.id.cancel_btn2).setOnClickListener(new HoistryListAdapter.locationButtonListener());
                })
                .setLayoutRes(R.layout.map_navagation_sheet)
                .setDimAmount(0.1f)            // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                .setCancelOutside(false)     // 点击外部区域是否关闭，默认true
                .setTag("DiTu");    // 设置DialogFragment的tag
        // .show();
    }

    private RefOrderListListener mRefOrderListListener;

    public void setRefOrderListListener(RefOrderListListener mRefOrderListListener) {
        this.mRefOrderListListener = mRefOrderListListener;
    }

    @Override
    protected void convert(BaseViewHolder holder, ListOrderInfo.DataBean.OrderItemBean item) {

        setCopyWay(holder.getView(R.id.history_item_dispatch_tv_order));
        setCopyWay(holder.getView(R.id.history_item_dispatch_tv_name));
        setCopyWay(holder.getView(R.id.history_item_dispatch_tv_sjh));
        setCopyWay(holder.getView(R.id.history_item_dispatch_tv_lxdh));
        setCopyWay(holder.getView(R.id.history_item_dispatch_tv_address));
        setCopyWay(holder.getView(R.id.history_item_dispatch_tv_sfnum));
        setCopyWay(holder.getView(R.id.history_item_dispatch_tv_scorder));
        setCopyWay(holder.getView(R.id.history_item_dispatch_tv_iccid));

        holder.setText(R.id.history_item_dispatch_tv_iccid, item.getIccid());
        holder.setText(R.id.history_item_dispatch_tv_scorder, item.getLt_order_sn());
        holder.setText(R.id.history_item_dispatch_tv_order, item.getOrder_sn());
        holder.setText(R.id.history_item_dispatch_tv_name, item.getUser_name());
        String tel = item.getPhonenum();
        LinearLayout telLayout = holder.getView(R.id.history_item_dispatch_ll_blhm);
        if (TextUtils.isEmpty(tel)) {
            telLayout.setVisibility(View.GONE);
        } else {
            telLayout.setVisibility(View.VISIBLE);
            holder.setText(R.id.history_item_dispatch_tv_sjh, tel);
        }
        holder.setText(R.id.history_item_dispatch_tv_lxdh, item.getBuyer_mobile());

        String address = item.getAddress();
        String remark = item.getRemark();

        String city = item.getCity();
        String status = item.getStatus();
        String orderNote = item.getOrder_note();
        // 增加证件号显示
        String user_idcard = item.getUser_idcard();

        LinearLayout llsfnum = holder.getView(R.id.history_item_dispatch_ll_sfnum);
        if (TextUtils.isEmpty(user_idcard)) {
            llsfnum.setVisibility(View.GONE);
        } else {
            llsfnum.setVisibility(View.VISIBLE);
            holder.setText(R.id.history_item_dispatch_tv_sfnum, user_idcard);
        }


        if ("0425".equals(city)) {
            if (!TextUtils.isEmpty(address)) {
                if (!TextUtils.isEmpty(remark)) {
                    remark = "  备注:" + remark;
                    String beizhu = address + remark;
                    SpannableString mp = new SpannableString(beizhu);
                    mp.setSpan(new ForegroundColorSpan(Color.RED), address.length() + 1,
                            beizhu.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);// 字体变色,包前不包后
                    holder.setText(R.id.history_item_dispatch_tv_address, mp);
                } else {
                    holder.setText(R.id.history_item_dispatch_tv_address, address);
                }
            }
        } else {
            if (!TextUtils.isEmpty(address)) {
                if (!TextUtils.isEmpty(remark)) {
                    remark = "  备注:" + remark;
                    String beizhu = address + remark;
                    SpannableString mp = new SpannableString(beizhu);
                    mp.setSpan(new ForegroundColorSpan(Color.RED), address.length() + 1,
                            beizhu.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);// 字体变色,包前不包后
                    holder.setText(R.id.history_item_dispatch_tv_address, mp);
                } else {
                    holder.setText(R.id.history_item_dispatch_tv_address, address);
                }
            }
        }

        holder.getView(R.id.history_item_dispatch_ll_iccid).setVisibility(View.GONE);
        holder.getView(R.id.history_item_dispatch_ll_scdd).setVisibility(View.GONE);
        holder.getView(R.id.history_item_dispatch_pd_cancle).setVisibility(View.GONE);
        TextView tv_state = holder.getView(R.id.history_item_dispatch_tv_state);
        tv_state.setVisibility(View.VISIBLE);
        tv_state.setText(orderNote);
        tv_state.setTextColor(mContext.getResources().getColor(R.color.orange));


        holder.setText(R.id.history_item_dispatch_tv_time, item.getLast_time());
        holder.setText(R.id.history_item_dispatch_tv_endtime, item.getGoods_name());
        holder.setOnClickListener(R.id.history_item_dispatch_tv_endtime, view -> {
            String note1 = item.getNote();// 获取订单说明
            String gdName = item.getGoods_name();// 获取订单说明

            PaiDanShuoMingDialog paiDanShuoMingDialog = new PaiDanShuoMingDialog(mActivity);
            paiDanShuoMingDialog.setContent(gdName, note1);
            paiDanShuoMingDialog.setCanceledOnTouchOutside(false);
            paiDanShuoMingDialog.setCancelable(false);
            paiDanShuoMingDialog.show();
        });

        holder.setOnClickListener(R.id.history_item_dispatch_pd_cancle, v -> {
            order_type = item.getOrder_type();
            TuiDanDialog tuiDanDialog = new TuiDanDialog(mContext, "提示", "", new TuiDanListListener() {
                @Override
                public void onCancleOrder(String str, int type) {
                    String orderSn = item.getOrder_sn();
                    // 确认取消
                    sureCancle(orderSn, 2, order_type);
                }
            });
            tuiDanDialog.setCanceledOnTouchOutside(false);
            tuiDanDialog.setCancelable(false);
            tuiDanDialog.show();
        });


        // 备注
        holder.setOnClickListener(R.id.history_item_dispatch_iv_beizhu, view -> {
            String orderSn = item.getOrder_sn();
            SelectDataUtils.showBeiZhuDialog(mActivity, new BeiZhuListener() {

                @Override
                public void onBeiZhuBack(String str, String data) {
                    subBeiZhu(item, orderSn, str, data);
                }
            });
        });

        holder.setOnClickListener(R.id.history_item_dispatch_iv_phone, v -> {
            buyerMobil = item.getBuyer_mobile();
            if (!TextUtils.isEmpty(buyerMobil)) {
                TuiDanDialog tuiDanDialog = new TuiDanDialog(mContext, "提示", buyerMobil, new TuiDanListListener() {
                    @Override
                    public void onCancleOrder(String str, int type) {
                        final String orderSn = item.getOrder_sn();
                        App.getApp().getHttpTools().callPhoneData(orderSn, new RequestCallBack() {
                            @Override
                            public void onSuccess(Object s) {
                                Log.e("项目异常", "------callPhoneData------" + s);
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                Log.e("项目异常", "------callPhoneData----onError--" + ex.toString());
                            }

                            @Override
                            public void onCancelled(Callback.CancelledException cex) {

                            }

                            @Override
                            public void onFinished() {

                            }
                        });
                        mAddPhoneNumItemListener.setPremmsionItemListener(buyerMobil);
                    }
                });
                tuiDanDialog.setCanceledOnTouchOutside(false);
                tuiDanDialog.setCancelable(false);
                tuiDanDialog.show();
            } else {
                ToastUtils.showShortToast(mContext, "电话号码为空");
            }
        });

        holder.getView(R.id.history_item_dispatch_tv_map).setTag(item);
        holder.setOnClickListener(R.id.history_item_dispatch_tv_map, view -> {

            if (!locationDialog.isVisible()) {
                curentItem = (ListOrderInfo.DataBean.OrderItemBean) view.getTag();
                locationDialog.show();
            }
        });
    }

    private void initPopupWindow() {
        View popupView = mActivity.getLayoutInflater().inflate(R.layout.tpl_select_menu, null);

        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(mActivity.getResources(), (Bitmap) null));

        TextView select_menu_copy = (TextView) popupView.findViewById(R.id.select_menu_copy);

        select_menu_copy.setOnClickListener(v -> {
            ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText(null, mCopiedText);
            Log.e("项目异常", "------mCopiedText------" + mCopiedText);
            cm.setPrimaryClip(clip);
            ToastUtils.showShortToast(mActivity, "内容已复制到剪切板,快去粘贴吧!");
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
        });
    }

    private void setCopyWay(final TextView tv) {
        tv.setOnLongClickListener(v -> {
            mCopiedText = ((TextView) v).getText().toString();
            popupWindow.showAsDropDown(v);
            return false;
        });
    }

    private AddPhoneNumItemListener mAddPhoneNumItemListener;

    public void setItemSelectListener(AddPhoneNumItemListener addPhoneNumItemListener) {
        mAddPhoneNumItemListener = addPhoneNumItemListener;
    }

    /**
     * 同步或取消
     *
     * @param orderSn
     * @param type    2代表取消
     */
    private void sureCancle(final String orderSn, final int type, final String orderType) {
        dialog.show();
        App.getApp().getHttpTools().tbOreCancle(type, orderSn, orderType, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("项目异常", "------sureCancle------" + result);
                if (dialog != null) {
                    dialog.dismiss();
                }
                try {

                    Gson gson = new Gson();
                    IdInfo info = gson.fromJson(result, IdInfo.class);
                    if (info != null) {
                        int code = info.getStatus();
                        if (code == 1) {
                            if (type == 1) {
                                // 同步只提示信息
                                ToastUtils.showShortToast(mActivity, info.getInfo());
                            } else {
                                ToastUtils.showShortToast(mActivity, info.getInfo());
                                // 取消需刷新界面
                                if (mRefOrderListListener != null) {
                                    mRefOrderListListener.onRefreshOrder();
                                }
                            }
                        } else if (code == 401) {
                            Boolean sucRef = RefReshToken.refshToken();
                            if (sucRef) {
                                sureCancle(orderSn, type, orderType);
                            } else {
                                RefReshToken.exitLogin();
                            }
                        } else {
                            ToastUtils.showShortToast(mActivity, info.getInfo());
                        }
                    } else {
                        ToastUtils.showShortToast(mActivity, "服务器返回数据为空");
                    }
                } catch (Exception e) {
                    ToastUtils.showShortToast(mActivity, "数据解析异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                ToastUtils.showShortToast(mActivity, "网络或服务器错误");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

        });

    }


    private class locationButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {

            try {

                LocationUtils locationUtils = new LocationUtils();
                locationUtils.setLatitude(Double.parseDouble(curentItem.getLast_gps_latitude().toString()));
                locationUtils.setLongitude(Double.parseDouble(curentItem.getLast_gps_longitude().toString()));
                if (!TextUtils.isEmpty(curentItem.getLt_address())) {

                    locationUtils.setName(curentItem.getLt_address());

                } else {
                    locationUtils.setName("");
                }
                LocationSDKTools sdkTools = new LocationSDKTools(mContext);

                switch (v.getId()) {
                    case R.id.baidu_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_BAIDU, locationUtils);
                        break;
                    case R.id.gaode_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_GAODE, locationUtils);
                        break;
                    case R.id.tencent_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_TENGXUN, locationUtils);
                        break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(mContext, "无法启动地图", Toast.LENGTH_SHORT).show();
            }
            locationDialog.dismiss();

        }
    }

    private void subBeiZhu(ListOrderInfo.DataBean.OrderItemBean item, final String orderSn,
                           final String remark, String data) {
        Log.e("项目异常", orderSn + "------subBeiZhu------" + remark + "---data---" + data);
        dialog.show();
        App.getApp().getHttpTools().beiZhu(orderSn, remark, data, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("项目异常", "------subBeiZhu------" + result);
                if (dialog != null) {
                    dialog.dismiss();
                }
                try {
                    Gson gson = new Gson();
                    IdInfo idInfo = gson.fromJson(result, IdInfo.class);
                    if (idInfo != null) {
                        if (idInfo.getStatus() == 1) {
                            item.setCity("0425");
                            item.setRemark(remark);
                            notifyDataSetChanged(); // 更新状态
                        } else if (idInfo.getStatus() == 401) {
                            Boolean sucRef = RefReshToken.refshToken();
                            if (sucRef) {
                                subBeiZhu(item, orderSn, remark, data);
                            } else {
                                RefReshToken.exitLogin();
                            }
                        } else {
                            ToastUtils.showShortToast(mActivity, idInfo.getInfo());
                        }

                    } else {
                        ToastUtils.showShortToast(mActivity, "服务器返回数据为空");
                    }
                } catch (Exception e) {
                    Log.e("项目异常", "数据解析异常:" + e.toString());
                    ToastUtils.showShortToast(mActivity, "数据解析异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.showShortToast(mActivity, "网络或服务器错误");
                if (dialog != null) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

        });
    }
}
